package com.lemon.smartsafetynew.ui.activity.base;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ListView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.event.base.NewAppEvent;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.GsonUtil;
import com.lemon.smartsafety.utils.LocationUtil;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.SystemUtil;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.SharedPreferencesHelper;
import com.lemon.smartsafety.utils.app.ToastUtil;
import com.lemon.smartsafety.utils.app.ToastUtils;
import com.lemon.smartsafety.utils.common.KeyBoardUtils;
import com.lemon.smartsafety.view.SwipeBackLayout;
import com.lemon.smartsafety.view.ViewFireCompanyNone;
import com.lemon.smartsafety.view.ViewListBtm;
import com.lemon.smartsafety.view.list.ListRefreshView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.ButterKnife;

/**
 * 项目名称：workspace
 * 类描述：
 * 创建人：Fargo
 * 创建时间：2016/8/8 14:01
 * 修改人：Fargo
 * 修改时间：2016/8/8 14:01
 * 修改备注：
 */
public abstract class NewBaseActivity extends AppCompatActivity {

    public static final String TAG = "BaseActivity";
    public static final int REF_VIEW = 0;
    public static final int SHOW_MSG = 1;
    public static final int HINT_KEYSTORY = 2;

    public String strShowMsg = "";

    public EventBus mBus;
    public Gson mGson;
    public Activity mActivity;
    /**
     * 提示信息对话框
     */
    public HUDUtil mHUDUtil;

    public ViewListBtm viewListBtm;

    public Intent intent;
    public Bundle bundle;
    public String RefreshTAG = "";

    public int page_size = 20;
    public int current_page = 1;
    public boolean bPutHttp = false;

    //是否在下拉
    //public boolean bPullDownHttp = false;

    public Toolbar mToolBar;
    public LocationUtil locationUtil;

    public SwipeBackLayout swipeBackLayout;

    public int mLoading = 0;
    protected SharedPreferencesHelper mSharedPreferencesHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //初始化View
        setContentView(getContentViewId());
        ButterKnife.bind(this);
        if (mHUDUtil == null) {
            mHUDUtil = new HUDUtil();
            mHUDUtil = mHUDUtil.init(NewBaseActivity.this);
            //mHUDUtil = HUDUtil.init(mContext);
        }
        mActivity = this;
        RefreshTAG = mActivity.getLocalClassName();
        //接受Bundle数据
        getBundleArgs();

        // register
        mBus.getDefault().register(this);
        mGson = GsonUtil.getCommonGson();
        mSharedPreferencesHelper = new SharedPreferencesHelper(IApplication.context());
        try {
            locationUtil = new LocationUtil(mActivity);
            ToastUtil.init(mActivity);
            ToastUtil.showShort();
        } catch (Exception e) {
            e.printStackTrace();
        }

        initToolBar();
        //initTitleView();
        initView();
        initHttp();

    }

    /**
     * 初始化标题
     */
    protected void initToolBar() {
        if (mToolBar == null) {
            mToolBar = getViewById(R.id.toolbar);
        }
        initTitleView();
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyBoardUtils.closeSoftInput(mActivity);
                callFinish();
            }
        });
    }

    /**
     * 初始化返回监听
     */
    protected void initSwipeBackLayout() {
        try {
            if (swipeBackLayout == null) {
                swipeBackLayout = getViewById(R.id.swipeBackLayout);
            }

            if (null != swipeBackLayout) {
                swipeBackLayout.setCallBack(new SwipeBackLayout.CallBack() {
                    @Override
                    public void onFinish() {
                        callFinish();
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void setBarTitle(int title) {
        mToolBar.setTitle(title);
    }


    public void setBarTitle(String title) {
        mToolBar.setTitle(title);
    }

    public void setSubBarTitle(String title) {
        mToolBar.setSubtitle(title);
    }

    public void setSubBarTitleColor(int Color) {
        mToolBar.setSubtitleTextColor(Color);
    }


    //获取传输的内容
    protected abstract void getBundleArgs();

    /**
     * 设置视图文件
     *
     * @return
     */
    protected abstract int getContentViewId();

    /**
     * 初始化顶部标题
     */
    protected abstract void initTitleView();

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 初始化网络请求
     */
    protected abstract void initHttp();

    /**
     * 初始化列表
     */
    protected abstract void initList();

    /**
     * 加载更多列表数据
     */
    protected abstract void loadList();

    /**
     * 刷新View
     */
    protected abstract void refreshView();

    /**
     * 结束Activity方法回掉
     */
    protected abstract void callFinish();

    public String toJson(Object o) {
        return mGson.toJson(o);
    }

    public void showLoading(String strHint) {

        try {
            mLoading = mLoading + 1;
            if (mHUDUtil != null) {
                mHUDUtil.showHUD();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void dismissLoading() {
        try {
            mLoading = mLoading - 1;
            if (mHUDUtil != null & mLoading == 0) {
                mHUDUtil.hidden();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 错误的情况下 刷新
     * @param viewFireCompanyNone  针对特殊情况
     * @param swipeLayout
     * @param isShowError   是否显示 空的错误提示条件
     * @param title   错误提示条件标题
     */
    public void errorInitView(ViewFireCompanyNone viewFireCompanyNone,SwipeRefreshLayout swipeLayout,boolean isShowError,String title) {

        if (isShowError) {
            viewFireCompanyNone.setVisibility(View.VISIBLE);
            showSwipLayout(swipeLayout,false);
            if (CommonUtil.strIsEmpty(title)) {
                viewFireCompanyNone.setContent("没有更多数据");
                viewFireCompanyNone.setSearch("重试");
            } else {
                viewFireCompanyNone.setContent(title);
                viewFireCompanyNone.setSearch("重试");
            }
            viewFireCompanyNone.setAllClick(new ViewFireCompanyNone.AllClick() {
                @Override
                public void click() {
                    initList();
                }
            });
        } else {
            viewFireCompanyNone.setVisibility(View.GONE);
            showSwipLayout(swipeLayout,true);
        }
    }


    /**
     * 错误的情况下 刷新
     * @param viewFireCompanyNone
     * @param view
     * @param isShowError   是否显示 空的错误提示条件
     * @param title   错误提示条件标题
     */
    public void errorInitView(ViewFireCompanyNone viewFireCompanyNone,View view,boolean isShowError,String title) {

        if (isShowError) {
            viewFireCompanyNone.setVisibility(View.VISIBLE);
            view.setVisibility(View.GONE);
            if (CommonUtil.strIsEmpty(title)) {
                viewFireCompanyNone.setContent("没有更多数据");
                viewFireCompanyNone.setSearch("重试");
            } else {
                viewFireCompanyNone.setContent(title);
                viewFireCompanyNone.setSearch("重试");
            }
            viewFireCompanyNone.setAllClick(new ViewFireCompanyNone.AllClick() {
                @Override
                public void click() {
                    initList();
                }
            });
        } else {
            viewFireCompanyNone.setVisibility(View.GONE);
            view.setVisibility(View.VISIBLE);
        }
    }





    @Subscribe
    public void onEventMainThread(NewAppEvent event) {
    }


    public void initLoadeRefresh(final ListRefreshView listView) {
        listView.setScrollBottomListener(new ListRefreshView.ScrollBottomListener() {
            @Override
            public void scrollBottom() {

                loadList();
                showUpLoad(true, listView);
                LogUtils.LOGE("上啦加载更多");

            }
        });

    }


    public void initSwipRefresh(final SwipeRefreshLayout swipeLayout) {

        swipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);


        swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {

                        initList();
                        swipeLayout.setRefreshing(false);
                    }
                }, 1000);
            }
        });

    }


    /**
     * 是否显示下拉刷新布局
     * @param swipeLayout
     * @param isShow
     */
    public void showSwipLayout(SwipeRefreshLayout swipeLayout,boolean isShow){
        if(swipeLayout==null){
            return;
        }

        if(isShow){
            swipeLayout.setVisibility(View.VISIBLE);
        }else{
            swipeLayout.setRefreshing(false);
            swipeLayout.setVisibility(View.GONE);
        }

    }



    /**
     * @param v 显示加载更多
     */
    public void showUpLoad(boolean v, ListView listView) {
        if (viewListBtm == null) {
            viewListBtm = new ViewListBtm(mActivity);
        }

        try {
            if (v) {
                if (bPutHttp) {
                    if (listView.getFooterViewsCount() == 0)
                        listView.addFooterView(viewListBtm);
                }
            } else {
                if (!bPutHttp) {
                    if (listView.getFooterViewsCount() != 0)
                        listView.removeFooterView(viewListBtm);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 查找View
     *
     * @param id   控件的id
     * @param <VT> View类型
     * @return
     */
    protected <VT extends View> VT getViewById(@IdRes int id) {
        return (VT) findViewById(id);
    }

    public MaterialDialog.Builder getConfirmDialog(String content, MaterialDialog.SingleButtonCallback callback) {
        return new MaterialDialog.Builder(this).title(getString(R.string.tip_str_title))
                .content(content)
                .positiveText(R.string.sure_str)
                .negativeText(R.string.cancel_str)
                .onAny(callback);
    }

    public void replaceFragment(int fragmentId, Fragment fragment) {
        getSupportFragmentManager().beginTransaction()
                .replace(fragmentId, fragment, fragment.getClass().getName())
                .commit();
    }


    /**
     * @param content
     * @param positiveText 点击确定的字符串
     * @param negativeText 点击取消的字符串
     * @param callback
     * @return
     */
    public MaterialDialog.Builder getConfirmDialog(String content, int positiveText, int negativeText, MaterialDialog.SingleButtonCallback callback) {
        return new MaterialDialog.Builder(this).title(getString(R.string.tip_str_title))
                .content(content)
                .positiveText(positiveText)
                .negativeText(negativeText)
                .onAny(callback);
    }


    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case REF_VIEW:
                    refreshView();
                    break;
                case SHOW_MSG:
                    ToastUtils.toastMsg(strShowMsg);
                    break;
                case HINT_KEYSTORY:
                    SystemUtil.HideKeyboard(mActivity);
                    break;
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();


        try {
            mBus.getDefault().unregister(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {

            if (mHUDUtil != null) {
                mHUDUtil.hidden();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
